<?php

namespace Viettrans\FrontBundle\Services;

use Symfony\Component\Form\Extension\Core\ChoiceList\ChoiceListInterface;

use Viettrans\FrontBundle\Services\MyCacheManager;

class MyChoicesListManager {
    private $options;
    private $myCacheManager;
    private $t;
	
    public function __construct(MyCacheManager $myCacheManager, $translator) {
        $this->myCacheManager = $myCacheManager;
		$this->t = $translator;
    }
    
    /**
     * Use function getCategories for generate $this->choices then return $this
     * This means this function returns an object of ChoiceListInterface
     * Then function getChoices() of ChoiceListInterface get the $this->choices
     * 
     * @param type $options
     * @return MyChoicesListManager implements ChoiceListInterface
     */
    public function getCategories($groupSelectable = false, $optionAll = false) {
		$t = $this->t;
	
        $choices = array();
        $groups = array();
        
        $_categoriesCached = $this->myCacheManager->getCategories();
                
        if ($optionAll) {
            $choices[0] = $t->trans('Tất cả danh mục');
        }

        if($groupSelectable) {
            foreach($_categoriesCached as $category) {
                $choices[$category['id']] = '---'.$category['name'].'---';

                foreach ($category['childs'] as $child) {
                    $choices[$child['id']] = $child['name'];
                }
            }
            
        } else {
            foreach($_categoriesCached as $category) {
                $childs = array();
                $_childs = $category['childs'];
                if(empty($_childs)) {
                    $choices[$category['id']] = $category['name'];
                    
                } else {
                    foreach ($_childs as $child) {
                        $childs[$child['id']] = $child['name'];
                    }

                    $choices[$category['name']] = $childs;
                }
            }
        }

        return new MyChoices($choices);
    }
    
    public function getTypes($options = array()) {
		$t = $this->t;
		
        $this->options = $options;
        $choices = array();
 
        $_typesCached = $this->myCacheManager->getTypes();

        foreach($_typesCached as $type) {
            $choices[$type['id']] = $t->trans($type['name']);
        }

        return new MyChoices($choices);
    }
}

class MyChoices implements ChoiceListInterface {
    private $choices;
    
    public function __construct(Array $choices) {
        $this->choices = $choices;
    }
    
    public function getChoices() {
        return $this->choices;
    }
}